package com.usian.controller;

import com.usian.pojos.Course;
import com.usian.pojos.Student;
import com.usian.service.CourseService;
import com.usian.service.StudentService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;


@RestController
public class UploadController {
    @Autowired
    private StudentService studentService;
    @Autowired
    private CourseService courseService;
    @PostMapping("/upload")
    @Transactional
    public String upload(@RequestBody MultipartFile file) throws IOException {

            Workbook sheets = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = sheets.getSheetAt(0);
//             导入学生表
        int num = sheet.getLastRowNum();

        ArrayList<Student> students = new ArrayList<>();
        for (int i = 1; i <= num; i++) {
            Row row = sheet.getRow(i);

            String name = row.getCell(0).getStringCellValue();
            int age =(int) row.getCell(1).getNumericCellValue();
            String sex = row.getCell(2).getStringCellValue();
            Student student = new Student();
            student.setAge(age+"");
            student.setSex(sex);
            student.setName(name);
            students.add(student);
        }
        studentService.saveList(students);
//          导入课程表
        sheet = sheets.getSheetAt(1);
        num = sheet.getLastRowNum();
        ArrayList<Course> courses = new ArrayList<Course>();
        for (int i = 1; i <= num; i++) {
            Row row = sheet.getRow(i);

            String name = row.getCell(0).getStringCellValue();
            Course course = new Course();
            course.setName(name);
            courses.add(course);
        }
        courseService.saveList(courses);

      return "success";
    }
    @PostMapping("/upload1")
    @Transactional
    public String upload1(@RequestBody MultipartFile file) throws IOException {
        Workbook sheets = new XSSFWorkbook(file.getInputStream());

        return "success";
    }


}
